package com.fishingwithme.android.ui.screens.harvest

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.fishingwithme.android.R
import com.fishingwithme.android.data.model.ApproveRuleItem
import com.fishingwithme.android.data.model.City
import com.fishingwithme.android.ui.theme.AppDimensions

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HarvestApprovalContent(
    selectedCities: SnapshotStateList<City>,
    isApproved: Boolean,
    searchQuery: String,
    searchResults: SnapshotStateList<City>,
    isSearching: Boolean,
    onSearchQueryChange: (String) -> Unit,
    onCitySelected: (City) -> Unit,
    onCityRemoved: (City) -> Unit,
    onApprovalChanged: (Boolean) -> Unit,
    onSubmit: (ruleItemId: Long, reason: String) -> Unit,
    onCancel: () -> Unit,
    rulesItems: List<ApproveRuleItem> = emptyList(),
    isRulesLoading: Boolean = false,
    onLoadRulesItems: () -> Unit = {},
    selectedReason: ApproveRuleItem? = null,
    onReasonSelected: (ApproveRuleItem) -> Unit = {}
) {
    // State for reason selection when rejected
    var showReasonDropdown by remember { mutableStateOf(false) }

    // When approval status changes, load rules if rejected
    LaunchedEffect(isApproved) {
        if (!isApproved) {
            onLoadRulesItems()
        }
    }

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(AppDimensions.SPACING_16)
            .verticalScroll(rememberScrollState())
    ) {
        // Title
        Text(
            text = stringResource(R.string.approval),
            style = MaterialTheme.typography.headlineSmall,
            fontWeight = FontWeight.Bold,
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = AppDimensions.SPACING_16)
        )

        // Search input for cities
        OutlinedTextField(
            value = searchQuery,
            onValueChange = onSearchQueryChange,
            label = { Text(stringResource(R.string.search_cities)) },
            leadingIcon = {
                Icon(
                    imageVector = Icons.Default.Search,
                    contentDescription = stringResource(R.string.search)
                )
            },
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = AppDimensions.SPACING_16)
        )

        // Selected cities list
        Text(
            text = stringResource(R.string.selected_cities),
            style = MaterialTheme.typography.titleMedium,
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = AppDimensions.SPACING_8)
        )

        if (selectedCities.isEmpty()) {
            Text(
                text = stringResource(R.string.no_cities_selected),
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = AppDimensions.SPACING_16)
            )
        } else {
            LazyColumn(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = AppDimensions.SPACING_16)
                    .heightIn(max = 150.dp)
            ) {
                items(selectedCities) { city ->
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(vertical = AppDimensions.SPACING_4),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = city.city ?: stringResource(R.string.unknown_city_name),
                            style = MaterialTheme.typography.bodyLarge,
                            modifier = Modifier.weight(1f)
                        )
                        IconButton(onClick = { onCityRemoved(city) }) {
                            Icon(
                                imageVector = Icons.Default.Close,
                                contentDescription = stringResource(R.string.remove)
                            )
                        }
                    }
                }
            }
        }

        // Search results
        if (isSearching) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = AppDimensions.SPACING_16),
                contentAlignment = Alignment.Center
            ) {
                CircularProgressIndicator()
            }
        } else if (searchResults.isNotEmpty()) {
            Text(
                text = stringResource(R.string.search_results),
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = AppDimensions.SPACING_8)
            )
            LazyColumn(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = AppDimensions.SPACING_16)
                    .heightIn(max = 200.dp)
            ) {
                items(searchResults) { city ->
                    Card(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(vertical = AppDimensions.SPACING_2),
                        onClick = { onCitySelected(city) },
                        colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.surface
                        )
                    ) {
                        Text(
                            text = city.city ?: stringResource(R.string.unknown_city_name),
                            style = MaterialTheme.typography.bodyLarge,
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(AppDimensions.SPACING_16)
                        )
                    }
                }
            }
        }

        // Approval checkbox
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = AppDimensions.SPACING_16),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Checkbox(
                checked = isApproved,
                onCheckedChange = onApprovalChanged
            )
            Spacer(modifier = Modifier.width(AppDimensions.SPACING_8))
            Text(
                text = if (isApproved) stringResource(R.string.approved) else stringResource(R.string.rejected),
                style = MaterialTheme.typography.bodyLarge
            )
        }

        // Reason selection dropdown when rejected
        if (!isApproved) {
            if (isRulesLoading) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = AppDimensions.SPACING_16),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator()
                }
            } else if (rulesItems.isNotEmpty()) {
                ExposedDropdownMenuBox(
                    expanded = showReasonDropdown,
                    onExpandedChange = { showReasonDropdown = it },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = AppDimensions.SPACING_16)
                ) {
                    OutlinedTextField(
                        modifier = Modifier
                            .fillMaxWidth()
                            .menuAnchor(),
                        readOnly = true,
                        value = selectedReason?.name ?: stringResource(R.string.select_reason),
                        onValueChange = {},
                        label = { Text(stringResource(R.string.reason_for_rejection)) },
                        trailingIcon = {
                            ExposedDropdownMenuDefaults.TrailingIcon(expanded = showReasonDropdown)
                        }
                    )
                    ExposedDropdownMenu(
                        expanded = showReasonDropdown,
                        onDismissRequest = { showReasonDropdown = false }
                    ) {
                        rulesItems.forEach { rule ->
                            DropdownMenuItem(
                                text = { Text(rule.name) },
                                onClick = {
                                    onReasonSelected(rule)
                                    showReasonDropdown = false
                                }
                            )
                        }
                    }
                }
            }
        }

        // Action buttons
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = AppDimensions.SPACING_16),
            horizontalArrangement = Arrangement.End
        ) {
            TextButton(onClick = onCancel) {
                Text(stringResource(R.string.cancel))
            }
            Spacer(modifier = Modifier.width(AppDimensions.SPACING_8))
            TextButton(
                onClick = {
                    // Pass the rule item ID and reason to the onSubmit callback
                    if (isApproved) {
                        // For approved items, use default values
                        onSubmit(1L, "Approved")
                    } else {
                        // For rejected items, use the selected reason
                        val ruleItemId = selectedReason?.id?.toLongOrNull() ?: 1L
                        val reason = selectedReason?.name ?: "Rejected"
                        onSubmit(ruleItemId, reason)
                    }
                },
                enabled = selectedCities.isNotEmpty()
            ) {
                Text(stringResource(R.string.submit))
            }
        }

        // Add some bottom padding to ensure buttons are visible
        Spacer(modifier = Modifier.height(AppDimensions.SPACING_16))
    }
}